#include "gpio.h"
#include "cs1237.h"
#include "clock.h"
#include "log.h"
#include "cs1259B.h"
/********************定义控制端口**********************/
#define  CS_SDA_PIN         GPIO_P20
#define  CS_SCL_PIN         GPIO_P18
/********************定义数据*************************/
#define	CS12X_SCL_HIGH()		HalGpioSet(CS_SCL_PIN,Bit_ENABLE)
#define	CS12X_SCL_LOW()			HalGpioSet(CS_SCL_PIN,Bit_DISABLE)
#define	CS12X_SDA_HIGH()		HalGpioSet(CS_SDA_PIN,Bit_ENABLE)
#define	CS12X_SDA_LOW()			HalGpioSet(CS_SDA_PIN,Bit_DISABLE)
#define	CS12X_SDA_OUTPUT()		HalGpioPinInit(CS_SDA_PIN,GPIO_OUTPUT);HalGpioPupdConfig(CS_SDA_PIN, GPIO_FLOATING)
#define	CS12X_SDA_INPUT()		HalGpioPinInit(CS_SDA_PIN,GPIO_INPUT);HalGpioPupdConfig(CS_SDA_PIN, GPIO_PULL_UP)
#define	CS12X_SDA_DATA()		HalGpioGet(CS_SDA_PIN)
//===================================================================================
CS1237_t Cs1237Cofig={
	.Flag.Byte = 0,
};
//---------------------------------------------------
void fun_1237_Init(void)
{
	CS12X_SDA_INPUT();
	HalGpioPinInit(CS_SCL_PIN,GPIO_OUTPUT);
	CS12X_SCL_LOW();
}

void fun_1237_POWEROFF(void)
{
	CS_unRegisterADTrage();
	// CS12X_SDA_HIGH();
	// CS12X_SDA_OUTPUT();
	CS12X_SCL_HIGH();
	// CS12X_SDA_HIGH();
}

void c1237_Inclk(void)
{
	CS12X_SCL_LOW();
	WaitUs(2);
	CS12X_SCL_HIGH();
	WaitUs(2);
	CS12X_SCL_LOW();
	WaitUs(2);
}

unsigned int Read1237Adc( CS1237_t* const config)
{
	uint8_t i = 0;
	uint32_t Data = 0;
	uint8_t cmd = 0;
	for(i = 0;i<24;i++)
	{
		c1237_Inclk();
		Data <<= 1;
		if(CS12X_SDA_DATA())
			Data |= 0x01;
		else
			Data &= (~0x01);
	}
	if(config != NULL)
	{
		for(; i< 29 ;i++)
		{
			c1237_Inclk();
		}
		CS12X_SDA_OUTPUT();
		if(config->Flag.Bit.WriteConfig)
		{
			cmd = write_command;
		}else{
			cmd = read_command;
		}
		for(;i<36;i++)
		{
			if(cmd & 0x40)
				CS12X_SDA_HIGH();
			else
				CS12X_SDA_LOW();
			c1237_Inclk();
			cmd <<= 1;
		}

		if(!config->Flag.Bit.WriteConfig)
		{
			CS12X_SDA_INPUT();
			cmd = 0;
		}else{
			cmd = config->config;
		}
		c1237_Inclk();//第37CLK
		i++;
		for(;i<45;i++)
		{
			if(config->Flag.Bit.WriteConfig)
			{
				if(cmd & 0x80)
					CS12X_SDA_HIGH();
				else
					CS12X_SDA_LOW();
				c1237_Inclk();
				cmd <<= 1;
			}else{
				cmd <<= 1;
				c1237_Inclk();
				if(CS12X_SDA_DATA())
					cmd |= 0x01;
				else
					cmd &= (~0x01);
			}
		}
		if(!config->Flag.Bit.WriteConfig)
		{
			config->config = cmd;
		}
		c1237_Inclk();//第46CLK
		CS12X_SDA_INPUT();
	}
	Data = 0 - Data;
	Data += 0x800000;
	Data &= 0xFFFFFF;
	// temp >>= 8;
	return Data;
}



















